<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\newagk\interfaces\AdminQbankServiceIf;
use com\gdl\newagk\dataobject\adminqbank\QbankDTO; 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * 题库后台接口 
 * 包含列表 修改 添加 更新题库
 */
class api_AdminQbankService extends api_Abstract implements AdminQbankServiceIf{ 
    /**
     * 题库列表
     */
    public function qbankList(QbankDTO $qbank)
    { 
        $platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : 0;
        $where = $qbank->where ? $qbank->where : "";
        $offset =  $qbank->offset ? gdl_lib_BaseUtils::getStr($qbank->offset, 'int') : 0;
		$num =  $qbank->num ? gdl_lib_BaseUtils::getStr($qbank->num, 'int') : 10;
		$allFiled = $qbank->update ? $qbank->update: ''; # 用于赛选其他平台
		
		
		$sharing = $qbank->userid ? gdl_lib_BaseUtils::getStr($qbank->userid, 'int') : 0; # 来自于云题库的赛选
		$ifSharing = $qbank->filed ? gdl_lib_BaseUtils::getStr($qbank->filed) : 0; # 是否来自云题库
		
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = []; 
		//if($allFiled!="all" && !empty($allFiled)){
		//	$likeName = $allFiled;
			
			//var_dump(htmlspecialchars($likeName));exit;
			#查询题库模糊查询
			//$where.=" and agk_qbank.name like '%".trim($likeName)."%' ";
		//}
		
		if(empty($platformId) || empty($where)){
			$result->message = "缺少必要参数";
			//return $result;
		}
		
        try{
			# 分页
			if($offset=='0') $offset=1;
			$rows = $num;
			$limit = ($offset - 1) * $rows . "," . $rows;
			//$group = 'order by agk_qbank.sort desc limit '.$limit;
			$group = 'order by agk_qbank.sort desc,agk_qbank.id desc limit '.$limit; 
			# 题库原始数据
			$qbankModel = new model_newagk_qbank();
			$leftJoin = array('agk_questions_binding as uc' => 'agk_qbank.id=uc.bankid');
			$condition = $where;
			$filed = "agk_qbank.id,agk_qbank.name,agk_qbank.platformId,agk_qbank.adminName,agk_qbank.adminUser,agk_qbank.parentId,agk_qbank.status,agk_qbank.issharing,FROM_UNIXTIME(agk_qbank.updateTime, '%Y年%m月%d日') as updateTime,agk_qbank.admin_reg,agk_qbank.total,agk_qbank.thumb,agk_qbank.qbankPid,agk_qbank.version";
			# 打断他获取题库列表
			if($allFiled=='all'){
				$num = 1000;
				$filed = "agk_qbank.id,agk_qbank.name";
				$list = $qbankModel->select($condition,$filed, $group,'',$leftJoin)->items;
				$result->code = 200;
				$result->message = "获取成功";
				$result->data = $list;
				return $result;
			} 
			$list = $qbankModel->select($condition,$filed, $group,'',$leftJoin)->items;
			
			$listCount = $qbankModel->select($condition,'count(agk_qbank.id) as num', '','',$leftJoin)->items; 
			# 组装数据
			$platformModel = new model_newagk_platform();
			$platformList = $platformModel->select("isdelete = 0","id,name,reals")->items;
			# 全部题库 
			$Alllist = $qbankModel->select("isdelete=0","id,name,platformId,qbankPid,version")->items; 
			$drawquestion = new service_drawquestion();
			$quesModel = new model_newagk_questions();
			for($i=0; $i<count($list); $i++){ 
				$list[$i]['parentName'] = "顶级题库";
				$list[$i]['parentNameId'] = 0;# 上级题库id
				$list[$i]['sharingQbankName'] = "无法找到顶级题库"; # 分享题库上级题库名 
				$list[$i]['sharingQbankId'] = 0; # 分享题库上级题库id
				$list[$i]['platformName'] = "无法找到顶级平台"; # 分享题库上级平台 or 题库平台名 or 总平台
				$list[$i]['name'] = $drawquestion->deleteHtml($list[$i]['name']);
				# 统计题目数量
				$questionWhere = "isdelete=0 and qbankId=".$list[$i]['id']."";
				$ques = $quesModel->selectOne($questionWhere, 'count(id) as num');
				if($ques){
					$qbankModel->update('id='.$list[$i]['id'], ['total'=>$ques['num']]);
				}
				
				if($list[$i]['platformId']==0){
					$list[$i]['platformName'] = "总平台"; 
				} 
				$list[$i]['isnew'] = 0; # 是否更新 1：需要更新 0：不需要更新
				# 是否为顶级题库
				for($j=0; $j<count($Alllist); $j++){
					if($list[$i]['parentId']!=0){
						if($list[$i]['parentId']==$Alllist[$j]['id']){
							$list[$i]['parentName'] = $Alllist[$j]['name'];
							$list[$i]['parentNameId'] = $Alllist[$j]['id'];
						}
					}
					# 找出分享题库的上级题库
					if($list[$i]['qbankPid']!=0){
						# 找出被分享题库
						if($list[$i]['qbankPid']==$Alllist[$j]['id']){
							$list[$i]['sharingQbankName'] = $Alllist[$j]['name']; # 分享题库上级题库名 
							$list[$i]['sharingQbankId'] = $Alllist[$j]['id']; # 分享题库上级题库id
							$list[$i]['sharingPid'] = $Alllist[$j]['platformId']; # 获取顶级题库的平台id
							# 查看被分享题库版本是否一致
							if($list[$i]['version']!=$Alllist[$j]['version']){
								$list[$i]['isnew'] = 1;
							}
						}						
					}
					# 是否更新 未添加 已添加 待更新 共享题库判断
					
				}
				# 平台来源
				for($k=0; $k<count($platformList); $k++){
					if($list[$i]['qbankPid']!=0){
						# 找出上级平台id 找出上级题库的平台名名称
						if($list[$i]['sharingPid']==$platformList[$k]['id']){
							$list[$i]['platformName'] = $platformList[$k]['reals']; 
						}
					}else{
						if($list[$i]['platformId']==0){
							$list[$i]['platformName'] = "总平台"; 
						}else{
							if($list[$i]['platformId']==$platformList[$k]['id']){
								$list[$i]['platformName'] = $platformList[$k]['reals']; 
							}
						}
					}
				}
			} 
				
			# 是否更新 未添加 已添加 待更新 共享题库判断 1：未添加 2：已添加 3：待更新
			if($ifSharing){
				$addList = []; # 添加了的数据
				$noList = []; # 没有添加
				$noNewList = []; # 没有更新的数据
				$yesNewList = []; #已近更新的数据
				for($ii =0; $ii<count($list); $ii++){
					  $list[$ii]['sharingIsAdd'] = 2; # 是否添加 1：已经添加 2:未添加
					  $list[$ii]['sharingIsNews'] = 2; # 没有更新
					for($kk=0; $kk<count($Alllist); $kk++){
						
						if($Alllist[$kk]['qbankPid']==@$list[$ii]['id'] && $Alllist[$kk]['platformId']==$platformId){
						    $list[$ii]['sharingIsAdd'] = 1; # 已近添加 
							if($Alllist[$kk]['version']==$list[$ii]['version']){
								$list[$ii]['sharingIsNews'] = 1; # 已经更新了
								$yesNewList[] = $list[$ii];
							}else{ 
							}
							$addList[] = $list[$ii]; # 已经添加的了
						}  
					}
				} 
				$resList = $list;
				# 查询出我下面的所有题库 
				$yesAddStr = [];
				foreach($addList as $key){
					$yesAddStr[] = $key['id'];
				}
				$myQbank = $qbankModel->select("isdelete=0 and platformId='{$platformId}' and qbankPid<>0",'id,name,platformId,qbankPid')->items;
				if($sharing==1){#未添加的=全部-已添加的
					
					for($i=0; $i<count($list); $i++){
						for($k=0; $k<count($myQbank); $k++){
							if(!in_array($list[$i]['id'],$yesAddStr) && $platformId==$myQbank[$k]['platformId']){ # 得到未添加的
								if(!empty($list[$i])){
									$noList[] = $list[$i];
								}
							}
						}
					}
					$resList = $noList;
				}
				if($sharing==2){ # 已添加
					$resList = $addList;
				}
				if($sharing==3){ # 未更新的
					$yesNewStr = [];
					foreach($yesNewList as $key){
						$yesNewStr[] = @$key['id'];
					}
					for($i=0; $i<count($list); $i++){
						for($k=0; $k<count($myQbank); $k++){ 
						
							if(!in_array(@$list[$i]['id'],$yesNewStr) && $platformId==@$myQbank[$k]['platformId'] && in_array(@$list[$i]['id'],$yesAddStr)){ # 得到未更新
								$noNewList[] = $list[$i];
							}
						}
					}
					$resList = $noNewList;
				}
				if($sharing==4){
					$resList = $yesNewList;
				}
			}else{
				$resList = $list;
			}
			//var_dump($listCount);exit;
			if($resList){
				$result->code = 200;
				$result->message = $listCount[0]['num'];
				$result->data = $resList;
			}else{
				$result->code = 200;
				$result->message = "暂无数据";
				$result->data = [];
			}
        } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage(); 
        }
        return $result; 
    }
    /**
     *  添加题库
     */
    public function addQbank(QbankDTO $qbank){ 
		$platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : 0;
		$adminId = $qbank->filed ? gdl_lib_BaseUtils::getStr($qbank->filed) : 1;
		$admin_reg = $qbank->where ? gdl_lib_BaseUtils::getStr($qbank->where) : ""; 
        $data = $qbank->data ? $qbank->data : "";
        $offset =  $qbank->offset ? gdl_lib_BaseUtils::getStr($qbank->offset, 'int') : 0;
		$num =  $qbank->num ? gdl_lib_BaseUtils::getStr($qbank->num, 'int') : 0;
		$sectionList = $qbank->update ?$qbank->update : 0;
		$sectionArray = json_decode($sectionList);
		$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
		$platformId = 0;
		if(empty($platformId) && empty($data)){
			$result->message = "缺少必要参数";
			return $result;
		}
		
        try{
			$qbankModel = new model_newagk_qbank();
			$data['remark'] = htmlspecialchars_decode($data['remark']);
			$res = $qbankModel->insert($data);
			
			if($res){
				$bingdingModel = new model_newagk_questionsbinding();
				$adminUserModel = new model_newagk_adminuser();
				
				# 向总平台插入一条 1 找到父亲平台插入一条父亲的管理员
				$bingdingData = [];
				
				$platformModel = new model_newagk_platform();
				$parentId = $platformModel->selectOne("id='{$platformId}'",'id,parentid');
				$adminUserId = $adminUserModel->selectOne("platform_id='{$parentId['parentid']}' and isdelete=0",'id');
				if($adminUserId['id']!=1){
					$bingdingData[]= array('bankid'=>$res,'adminUserId'=>$adminUserId['id']);
				}
				$bingdingData[]= array('bankid'=>$res,'adminUserId'=>$adminId);
				foreach($bingdingData as $key){
					$bingRet = $bingdingModel->insert($key);
				}
				# 添加成功后向题库生成章节
				$sectionModel = new model_newagk_sections();
				$insertSectionId  = [];
				for($i=0; $i<count($sectionArray); $i++){
					$insertSectionData = ['seName'=>$sectionArray[$i],'plformId'=>$platformId,'qbankId'=>$res,'admin_reg'=>$admin_reg,'admin_id'=>$adminId,'isdelete'=>0,'status'=>1];
					$insertSectionId[] = $sectionModel->insert($insertSectionData); 
				}
				$sectionStr = implode(",",$insertSectionId);
				$qbankModel->update('id='.$res,['qbankSections'=>$sectionStr]);
				
				$result->message = "添加题库成功";
				$result->code = 200;
				$result->data[]= ['id'=>$res?$res:0];
			}else{
				$result->message = "添加题库失败"; 
			}
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
    /**
     *  修改题库
     */
    public function editQbank(QbankDTO $qbank){
		$platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : 0;
		$qbankid = $qbank->userid ? gdl_lib_BaseUtils::getStr($qbank->userid) : "";
		$admin_reg = $qbank->where ? gdl_lib_BaseUtils::getStr($qbank->where) : "";
		$sectionList = $qbank->update ?$qbank->update : 0;
		$adminId = $qbank->filed ? gdl_lib_BaseUtils::getStr($qbank->filed) : 1;
		$sectionArray = json_decode($sectionList);
		$data = $qbank->data ? $qbank->data : "";
		$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
		
		if(empty($qbankid) || empty($data) || empty($admin_reg)){
			$result->message = "缺少必要参数";
			return $result;
		} 
        try{
           # update_time total
		   $qbankModel = new model_newagk_qbank();
		   $questionModel = new model_newagk_questions();
		   $condition = "qbankId='{$qbankid}' and isdelete=0";
		   $filed = "count(id) num";
		   $total = $questionModel->selectOne($condition,$filed);
		   $data['total'] = $total['num'] ? $total['num'] : 0;
		   if($platformId==0){
				$upwhere = "id = '{$qbankid}'";
		   }else{
				$upwhere = "id = '{$qbankid}' and admin_reg = '{$admin_reg}' and platformId='{$platformId}'";
		   }
		   $data['remark'] = htmlspecialchars_decode($data['remark']);
		   $upQbank = $qbankModel->update($upwhere, $data); 
		   $upversionId = $qbankModel->selectOne($upwhere,'version');
		   
		   # 修改试题内的章节
		   $sectionModel = new model_newagk_sections();
		   $insertSectionId  = [];
		   $deleteSectionId = [];
		   
		   for($i=0; $i<count($sectionArray); $i++){ 
			   if($sectionArray[$i]->id==0){ #新增
					$insertSectionData = ['seName'=>$sectionArray[$i]->seName,'plformId'=>$platformId,'qbankId'=>$qbankid,'admin_reg'=>$admin_reg,'admin_id'=>$adminId,'isdelete'=>0,'status'=>1];
					 $str = $sectionModel->insert($insertSectionData); 
					$deleteSectionId[] = $str;
					$insertSectionId[] = $str;
			   }else{ #修改
				   $updateSectionData = ['seName'=>$sectionArray[$i]->seName]; 
				   $sectionModel->update('id='.$sectionArray[$i]->id,$updateSectionData); 
				   $insertSectionId[] = $sectionArray[$i]->id;
				   $deleteSectionId[] = $sectionArray[$i]->id;
			   } 
		   }
		   $sectionStr = implode(",",$insertSectionId);
			if($deleteSectionId){
				$deleteStr = implode(",",$deleteSectionId);
				$sectionContion = "id not in (".$deleteStr.") and qbankId=".$qbankid;
				$sectionModel->update($sectionContion,['isdelete'=>1]);
			}
		   $upversionData['qbankSections'] = $sectionStr;
		   $upversionData['updateTime'] = time();
		   $upversionData['version'] = intval($upversionId['version'])+1;
		   $upversion = $qbankModel->update($upwhere,$upversionData);
		   $result->data[] = ['id'=>$qbankid?$qbankid:0];
		   if($upversion || $upQbank){
				$result->code =200;
				$result->message = "修改成功";
		   }else{
			   $result->message = "请勿重复修改";
		   }  
		   
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
    /**
     *  更新题库
     */
    public function updateQbank(QbankDTO $qbank){
		$platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : 0;
		$qbankId = $qbank->userid ? gdl_lib_BaseUtils::getStr($qbank->userid) : ""; # 当前分享题库id
		$qbankPid = $qbank->gdl_userid ? gdl_lib_BaseUtils::getStr($qbank->gdl_userid) : ""; # 被分享的题库PId
		$admin_reg = $qbank->where ? gdl_lib_BaseUtils::getStr($qbank->where) : "";
		
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
		if( empty($qbankId) || empty($qbankPid) || empty($admin_reg)){
			$result->message = "缺少必要参数";
			return $result;
		}
        try{
			$qbankModel = new model_newagk_qbank();
			$questionModel = new model_newagk_questions();
			$answerModel = new model_newagk_questionsanswer();
			# 根据分享题库查询出他上级的题库
			$getQbankPid = $qbankModel->selectOne("id=".$qbankId,'qbankPid');
			$qbankPid = $getQbankPid['qbankPid'] ? $getQbankPid['qbankPid'] : $qbankPid;
			if(empty($qbankPid)){
				$result->message = "未找到云题库";
				return $result;
			}
            $qbankList = $qbankModel->select("id in ('".$qbankId."','".$qbankPid."') and isdelete=0", "id,platformId,version")->items;
			# 开始更新题库
			if($qbankList[0]['version']!=$qbankList[1]['version']){
				$qbankInfo = $qbankModel->selectOne("id='{$qbankPid}' and isdelete=0","*");
				$questionFiled = "*";//"id,typeId,question,select,selectNumber,answer,describe,knowsName,sectionId,isdelete,level,quesTag,quesTagVal,status,pid,admin_id";
				$questionInfo = $questionModel->select("qbankId='{$qbankPid}'",$questionFiled)->items;
				$upQuestionsInfo = $questionModel->select("qbankId='{$qbankId}' and qbankPid='{$qbankPid}'", $questionFiled)->items; 
				if($qbankInfo){
					$data = [
						'platformId'=>$platformId, 
						'name'=>$qbankInfo['name'],
						'parentId'=>'0',
						'status'=>$qbankInfo['status'],
						'issharing'=>0,
						'remark'=>$qbankInfo['remark'],
						'updateTime'=>time(),
						'sort'=>$qbankInfo['sort'],
						'admin_reg'=>$admin_reg,
						'isdelete'=>$qbankInfo['isdelete'],
						'total'=>$qbankInfo['total'], #可能会出现bug 如果分享题库新增加了试题可能会缺少统计
						'thumb'=>$qbankInfo['thumb'],
						'qbankTag'=>$qbankInfo['qbankTag'],
						'qbankTagValue'=>$qbankInfo['qbankTagValue'],
						'qbankSections'=>$qbankInfo['qbankSections'],
					];
					# 更新题库
					$qbankRet = $qbankModel->update("id='{$qbankId}'",$data);
					#更新试题 暴力玩法删完子题库再添加新数据
					$deleteArray = [];
					foreach($upQuestionsInfo as $k=>$v){
						$deleteArray[] = $v['id'];
					}
					$deleteArrayStr = implode(",",$deleteArray);
					# 删除答案 删除试题 谨慎操作还有改进的空间
					$deleteAnswer = $answerModel->delete("questionsId in (".$deleteArrayStr.")");
					$deleteQuestion = $questionModel->delete("qbankId='{$qbankId}' and qbankPid='{$qbankPid}'");
					
					#添加一个默认章节
					$sectionModel = new model_newagk_sections();
					$insertSectionData = ['seName'=>'默认章节','plformId'=>$platformId,'qbankId'=>$qbankId,'admin_reg'=>$admin_reg,'admin_id'=>1,'isdelete'=>0,'status'=>1];
					$strId = $sectionModel->insert($insertSectionData); 
					
					# 复制试题和答案 
					$questionData = [];
					foreach($questionInfo as $k=>$v){
						$questionData = [
								'typeId'=>$v['typeId'],
								'qbankId'=>$qbankId,
								'question'=>$v['question'],
								'select'=>$v['select'],
								'selectNumber'=>$v['selectNumber'],
								'answer'=>$v['answer'],
								'knowsName'=>$v['knowsName'],
								'sectionId'=>$strId, # 重新生成一个默认章节
								'createTime'=>time(),
								'isdelete'=>0,
								'describe'=>$v['describe'],
								'level'=>$v['level'],
								'qbankPid'=>$qbankPid,
								'pid'=>$v['id'],
								'quesTag'=>$v['quesTag'],
								'quesTagVal'=>$v['quesTagVal'],
								'admin_id'=>$v['admin_id'],
								'status'=>$v['status'],
								'admin_reg'=>$admin_reg
						];
						$_select = self::exAnswerStrToArr($v['select']);
						$qid = $questionModel->insert($questionData); 
						//var_dump($questionModel);exit;
						# 插入答案
						if($v['typeId']==1 || $v['typeId']==2 || $v['typeId']==3){
							$answerFormat = '';
							foreach ($_select as $kw => $aw) { 
								$_answerData = array(
									'questionsId' => $qid,
									'option' => $kw ? $kw : 'UNKOWN',
									'answer' => $aw ? $aw : 'UNKOWN'
								);
								//处理答案选项为标准格式
								$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($aw).' ' : $kw.'.'.trim($aw);													
								$answerRet = $answerModel->insert($_answerData);
							}
						}
						 
					}
					 
					# 最后一步更新版本号
					$res = $qbankModel->update("id='{$qbankId}'",array('version'=>$qbankInfo['version']));
					if($res){
						$result->code = 200;
						$result->message = "更新成功";
					}
				}else{
					$result->message = "更新题库失败，上级题库不存在或已被禁用";
				}
				
			}else{
				$result->message = "该题库已是最新";
			}
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
     *  题库详情
     */
    public function qbankInfo(QbankDTO $qbank){
		$id =  $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id, 'int') : 0;
		
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = []; 
		$result->message = "未获取到数据";
		if(empty($id)){
			$result->message = "请带入正确的题库标识";
			return $result;
		}
		
        try{
			$qbankModel = new model_newagk_qbank();
			$qbankTagModel = new model_newagk_qbanktag();
			$condition['id'] = $id;
			$filed = "id,name,issharing,parentId,platformId,qbankPid,qbankSections,qbankTag,qbankTagValue,remark,sort,status,thumb,total,FROM_UNIXTIME(updateTime, '%Y年%m月%d日%h:%i:%s') as update_time";
			$res = $qbankModel->selectOne($condition,$filed); 
			if($res){
				$tagList = [];
				$tagValueList = [];
				# 组装标签
				if($res['qbankTag']){ 
					$inArray = $res['qbankTag'];
					$tagWhere = "isdelete = 0 and type=0 and (id in (".$inArray.") or pid in (".$inArray.") )";
					$tag = $qbankTagModel->select($tagWhere,'id,pid,tagName')->items;
							//var_dump($tag);exit;
					if($tag){
						$tagValue = explode(',',$res['qbankTagValue']);
						
						for($i=0; $i<count($tag); $i++){
							if($tag[$i]['pid']==0){								
								$tagList[] = ['id'=>$tag[$i]['id'],'pid'=>0, 'name'=>$tag[$i]['tagName']]; 
							}else{
								$_select = "no";
								if(in_array($tag[$i]['id'],$tagValue)){
									$_select = "select";
								}
								$tagValueList[] = ['id'=>$tag[$i]['id'],'pid'=>$tag[$i]['pid'], 'name'=>$tag[$i]['tagName'],'select'=>$_select]; ; 
							}
							
						}
					}
				}
				$res['qbankTag'] = json_encode($tagList);
				$res['qbankTagValue'] = json_encode($tagValueList);
				
				# 查询上级题库
				$res['parentName'] ="顶级题库";
				if($res['parentId']!=0){
					$pQbankName = $qbankModel->selectOne('id='.$res['parentId'],'id,name,status');
					$res['parentName'] = $pQbankName['name']?$pQbankName['name']:"未获取到上级题库";
					$res['parentStatus'] = $pQbankName['status']?$pQbankName['status']:0;
				}
				$drawquestion = new service_drawquestion();
				$res['remark'] = $drawquestion->deleteHtml($res['remark']);
				 
				# 组装章节
				if($res['qbankSections']){
					$sectionModel = new model_newagk_sections();
					$inSectionArray = $res['qbankSections'];
					//$inSectionStr = explode(',',$res['qbankSections']);
					//$inSectionArray = implode("','",$inSectionStr);
					//var_dump($inSectionArray);exit;
					# 分享题库 qbank_id变了
					//and qbank_id='{$id}'
					$sectionWhere = "isdelete = 0  and id in (".$inSectionArray.")";
					$fileds = "id,seName";
					$sectionList = $sectionModel->select($sectionWhere, $fileds)->items;
					$res['qbankSections'] = json_encode($sectionList);
				}
				$result->code = 200;
				$result->message = "获取成功";
				$result->data[] = $res;
			}
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
     *  加入我的题库
     */
    public function addMyQbank(QbankDTO $qbank){
		$platformId =  $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id, 'int') : 0;
		$adminUserIds = $qbank->userid ? gdl_lib_BaseUtils::getStr($qbank->userid, 'int') : 0;
		$admin_reg =  $qbank->filed ? gdl_lib_BaseUtils::getStr($qbank->filed) : "";
		$qbankId = $qbank->gdl_userid ? gdl_lib_BaseUtils::getStr($qbank->gdl_userid) : "";
		$data = $qbank->data ? $qbank->data : "";
		
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
        if( empty($admin_reg) || empty($qbankId)){
			$result->message = "缺少必要参数";
			return $result;
		}
		
        try{
			$qbankModel = new model_newagk_qbank();
			$questionModel = new model_newagk_questions();
			$qbankInfo = $qbankModel->selectOne("id='{$qbankId}' and isdelete=0","*");
			
			# 查询是否已经继承题库了
			$extex = $qbankModel->selectOne("qbankPid='{$qbankId}' and isdelete=0 and platformId ='{$platformId}'","id");
			if($extex){
				$result->message = "该题库已被分享，请勿重复分享";
				return $result;
			}
			
			if($qbankInfo['status']==1){
				$questionInfo = $questionModel->select("qbankId='{$qbankId}' and isdelete=0","*")->items;
				if($questionInfo){ 
					$data = [
						'platformId'=>$platformId, 
						'adminName'=>$data['name'],
						'adminUser'=>$data['user'],
						'name'=>$qbankInfo['name'],
						'parentId'=>'0',
						'status'=>$qbankInfo['status'],
						'issharing'=>$qbankInfo['issharing'],
						'remark'=>$qbankInfo['remark'],
						'createTime'=>time(),
						'updateTime'=>time(),
						'sort'=>$qbankInfo['sort'],
						'admin_id'=>$adminUserIds,
						'admin_reg'=>$admin_reg,
						'isdelete'=>$qbankInfo['isdelete'],
						'total'=>$qbankInfo['total'],
						'thumb'=>$qbankInfo['thumb'],
						'qbankPid'=>$qbankId,
						'qbankTag'=>$qbankInfo['qbankTag'],
						'level'=>$qbankInfo['level'],
						'qbankTagValue'=>$qbankInfo['qbankTagValue'],
						//'qbankSections'=>$qbankInfo['qbankSections'],
						'version'=>$qbankInfo['version'],
					];
					# 复制题库
					$qbankRet = $qbankModel->insert($data); 
					#添加一个默认章节
					$sectionModel = new model_newagk_sections();
					$insertSectionData = ['seName'=>'默认章节','plformId'=>$platformId,'qbankId'=>$qbankId,'admin_reg'=>$admin_reg,'admin_id'=>1,'isdelete'=>0,'status'=>1];
					$strId = $sectionModel->insert($insertSectionData); 
					$qbankModel->update('id='.$qbankRet, ['qbankSections'=>$strId]); # 向集成的题库里加入章节
					
					# 复制试题和答案
					$answerModel = new model_newagk_questionsanswer();
					$questionData = [];
					foreach($questionInfo as $k=>$v){
						$questionData = [
								'typeId'=>$v['typeId'],
								'qbankId'=>$qbankRet,
								'question'=>$v['question'],
								'select'=>$v['select'],
								'selectNumber'=>$v['selectNumber'],
								'answer'=>$v['answer'],
								'knowsName'=>$v['knowsName'],
								'sectionId'=>$strId,
								'createTime'=>time(),
								'isdelete'=>0,
								'describe'=>$v['describe'],
								'level'=>$v['level'],
								'qbankPid'=>$qbankId,
								'pid'=>$v['id'],
								'quesTag'=>$v['quesTag'],
								'quesTagVal'=>$v['quesTagVal'],
								'admin_id'=>$v['admin_id'],
								'status'=>$v['status'],
								'admin_reg'=>$admin_reg
						];
						$_select = self::exAnswerStrToArr($v['select']);
						$qid = $questionModel->insert($questionData);
						//var_dump($questionModel);exit;
						# 插入答案
						if($v['typeId']==1 || $v['typeId']==2 || $v['typeId']==3){
								$answerFormat = '';
								foreach ($_select as $kw => $aw) { 
									$_answerData = array(
										'questionsId' => $qid,
										'option' => $kw ? $kw : 'UNKOWN',
										'answer' => $aw ? $aw : 'UNKOWN'
									);
									//处理答案选项为标准格式
									$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($aw).' ' : $kw.'.'.trim($aw);													
									$answerRet = $answerModel->insert($_answerData);
								}
						}
						
					}
					
					# 向总平台插入一条 1 找到父亲平台插入一条父亲的管理员
					$bingdingData = [];
					$bingdingModel = new model_newagk_questionsbinding();
					$adminUserModel = new model_newagk_adminuser();
					$platformModel = new model_newagk_platform();
					$parentId = $platformModel->selectOne("id='{$platformId}'",'id,parentid');
					$adminUserId = $adminUserModel->selectOne("platform_id='{$parentId['parentid']}' and isdelete=0",'id');
					if($adminUserId['id']!=1){
						$bingdingData[]= array('bankid'=>$qbankRet,'adminUserId'=>$adminUserId['id']);
					}
					$bingdingData[]= array('bankid'=>$qbankRet,'adminUserId'=>$adminId);
					foreach($bingdingData as $key){
						$bingRet = $bingdingModel->insert($key);
					}
					$result->code = 200;
					$result->message = "成功分享该题库，并复制全部试题";
					
				}else{
					$result->message = "该题库还没有添加任何试题";
					return $result;
				}
			}else{
				$result->message = "该题库无法被分享";
				return $result;
			}
			
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
     *  添加题库章节
     */
    public function addQbankSection(QbankDTO $qbank){
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
        
        try{
           
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
     *  添加题库标签
     */
    public function addQbankTag(QbankDTO $qbank){
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
        
        try{
           
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
     *  查询本题库下章节
     */
    public function selectQbankSection(QbankDTO $qbank){
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
        
        try{
           
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
     *  查询本地题库下标签
     */
    public function selectQbankTag(QbankDTO $qbank){
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];  
        
        try{
           
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	/**
	* 抽试题接口
	*/
	public function paperQuestions(QbankDTO $qbank){
		$platformId =  $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id, 'int') : 0;
		$where =  $qbank->where ? gdl_lib_BaseUtils::getStr($qbank->where) : "";
		$qbankId = $qbank->gdl_userid ? gdl_lib_BaseUtils::getStr($qbank->gdl_userid) : "";
		$count = $qbank->userid ? gdl_lib_BaseUtils::getStr($qbank->userid,'int') : 0;
        $result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];   
        if(empty($where)){
			$result->message = "缺少必要参数";
			return $result;
		}
        try{
           $questionModel = new model_newagk_questions();
		   $filed = "*";//"id,typeId,qbankId,question,select,selectNumber,answer,describe,level"; select 是关键字
		   $group = "order by typeId desc";
		   $quesList = $questionModel->select($where,$filed,$group)->items;
		   $result->message = "获取成功";
		   $result->code = 200;
		   if($count){
			   $newList = [];
			   for($i=0; $i<$count; $i++){
				   $key = mt_rand(0,$count-1);
				   $newList[]=$quesList[$key];
			   } 
			   $result->data = $newList;
			   
			   return $result;
		   }else{
			   $result->data[] = ['count'=>count($quesList)];
			   return $result;
		   }
        }catch(Exception $e){
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        
        return $result;
    }
	 
	//子集排序归类到child
	public function unlimitedForLayer($cate,$pid=0){
			$arr = array();
			foreach($cate as $v){ 
					if($v['pid']==$pid){
							$v['pid'] = $pid;
							if($v['id']){
								$v['child'] = self::unlimitedForLayer($cate,$v['id']);
								$arr[] = $v;
							}
							
					}
			}
			return $arr;
	}
	/*
		切割答案
	*/
	public  function exAnswerStrToArr($str='',$delimiter='!@#'){
		$anIndex =  array('A','B','C','D','E','F','G');		
		//$str = 'A.中国##|B.胡天';
		//有分隔符的情况
		$resultArr = array();
		
		if(substr_count($str,$delimiter)>0) {
			$arr = explode($delimiter,$str);
			foreach($arr as $val){
				$arrTemp = self::exAnswerStrToArrReg($val);					
				$resultArr = array_merge($resultArr,$arrTemp);				
			}			
		}
		//判断机制
		
		if(false=== self::selectAnswerPass($resultArr)) {$resultArr = self::exAnswerStrToArrReg($str);}
		return $resultArr;		
	}
	/**
	  切割答案
	*/
	public static function exAnswerStrToArrReg($str=''){
		$anIndex =  array('A','B','C','D','E','F','G');	

		//临时处理特殊符号，今后写好正则后取消
		$symbols = array('、','？');
		
		foreach($symbols as $val){
			$str = str_replace($val,'.',$str);
		}
		//无分隔的情况 有ABCDE加.的情况
		$arr =  preg_split('/([a-zA-Z]+\.)/',$str,-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
		$resultArr = array();
		$isKey = false; $skey='';
		foreach($arr as $val){
			if($isKey){$resultArr[$skey] = $val;$isKey = false;}
			$val = str_replace('.','',$val);
			$val = str_replace(PHP_EOL,'',$val);
			$val = trim($val);
			if(in_array($val,$anIndex)) {
				$isKey=true;
				$skey=$val;
			}			
		}
		return $resultArr;
	}
	/*
		切割答案
	*/
	public static function selectAnswerPass($arr){
		
		if(empty($arr)) return false;
		$anIndex =  array('A','B','C','D','E','F','G');		
		$countKey=0;
		$arrKey = array_keys($arr);
		
		foreach($arrKey as $val){
			if(in_array($val,$anIndex)) $countKey++;
		}
		return $countKey<=1 ? false :true;
	}	

   
}
